package com.lots.interceptor;

import com.lots.context.BaseContext;
import com.lots.properties.JwtProperties;
import com.lots.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    //执行前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //3. 获取请求头中的令牌（token）。
        String token = request.getHeader("token");

        //4. 判断令牌是否存在，如果不存在，返回错误结果（未登录）。
        if(!StringUtils.hasLength(token)){ //jwt为空
            log.info("获取到jwt令牌为空, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        //5. 解析token，如果解析失败，返回错误结果（未登录）。
        try {
            Claims  claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Object userIdObj = claims.get("userId");
            if (userIdObj == null) {
                log.warn("JWT 中缺少 userId，认证失败");
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                return false;
            }
            Long userId;
            if (userIdObj instanceof Number) {
                userId = ((Number) userIdObj).longValue(); // 兼容 int/long
            } else {
                try {
                    userId = Long.valueOf(userIdObj.toString());
                } catch (NumberFormatException e) {
                    log.warn("userId 格式不正确: {}", userIdObj);
                    response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                    return false;
                }
            }
            BaseContext.setCurrentId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //6. 放行。
        log.info("令牌合法, 放行");
        return true;
    }

    /**
     * 执行后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("执行后的操作");
        BaseContext.removeCurrentId();
    }
}
